##################################################################

# Gautam Nair
# gautam.nair@yale.edu
# Misperceptions of Relative Affluence and Support for International Transfers
# Make Table 11: Correlation Between Missing Response and Treatment Assignment

##################################################################

# setwd("")

##################################################################
# loading packages
##################################################################

library(Hmisc)
library(foreign)
library(sandwich)
library(lmtest)
library(numDeriv)
library(stargazer)
library(ggplot2)
library(plyr)
library(gridExtra)
library(ri)
library(dplyr)
library(plyr)
library(scales)

##################################################################

rm(list=ls())

data.working <- readRDS("d_r_cleaned_analysis_dataset.Rda")

data.working$rank.estimate.diff.10 <- data.working$rank.estimate.diff/10
data.working$median.estimate.top.100k.10000 <- data.working$median.estimate.top.100k.10000 - ((2100/10000))
data.working$median.estimate.top.100k.10000

vars1 <- c(
"group3",
"group2")

list.ind.group <- list(vars1)

dep.var <- c("q8.noresponse", "q9.noresponse", "q11.noresponse", "q13ab.noresponse", "q10.noresponse", "q12.noresponse", "q14.noresponse")
reg.models <-vector("list", length(dep.var)) 
se.models <-vector("list", length(dep.var))
matrix <- vector("list", length(dep.var))

x=0 

for(i in 1:length(dep.var)){
	for(y in 1:length(list.ind.group)){
		my.formula <-paste(dep.var[i],'~', paste(list.ind.group[[y]], collapse= ' + '))
		temp.model <- lm(my.formula, data=data.working)
		temp.se <- coeftest(temp.model, vcov=vcovHC(temp.model,type="HC2"))[,2]
		x = x+1
		se.models[[x]] <- temp.se
		reg.models[[x]] <- temp.model
	}
}

varlabels <-       c("Information", "Placebo", "Constant (Control Group Mean)" )
spectitle <- c("Treatment Assignment and Nonresponse Correlation")
outputfile <- c("tf_t_11_treatment_missingness_correlation.txt")
columnlabels <-c("Aid", "Ideal Spend.", "Ag. Protections", "Giving", "Domestic", "Social Desir.", "Norms")


stargazer(reg.models[[1]],  reg.models[[2]], reg.models[[3]], reg.models[[4]], reg.models[[5]], reg.models[[6]], reg.models[[7]],
          se=list(se.models[[1]],  se.models[[2]], se.models[[3]], se.models[[4]], se.models[[5]], se.models[[6]], se.models[[7]]),
         title= spectitle,
         type="text",
          out=outputfile,
          no.space=TRUE, 
          model.numbers= TRUE,
         notes.append=FALSE,
          align=FALSE,
         covariate.labels=varlabels,
          header= FALSE,
          font.size="footnotesize",
          model.names=TRUE,
          digits=2,
          omit.stat = c("rsq", "f","adj.rsq"),
          column.labels  = columnlabels,
          dep.var.caption  = "Proportion of Subjects Not Providing Response",
          dep.var.labels.include=FALSE,
         df=FALSE,
         omit.table.layout="n"
)   
 
